package com.lesson1.fangshua;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisKeyValueTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author liliang
 * @date 2019/11/3.
 */
@Component
public class FangshuaInterceptor extends HandlerInterceptorAdapter {


    @Resource
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            AccessLimit accessLimit = method.getMethodAnnotation(AccessLimit.class);
            if (accessLimit == null) {
                return true;
            }
            int seconds = accessLimit.seconds();
            int maxCount = accessLimit.maxCount();
            String url = request.getRequestURL().toString();

            Integer count = redisService.get(url, Integer.class);
            if(count == null){
                //第一次访问
                redisService.put(url,"1",seconds);
            }else if(count < maxCount){
                //加1
                redisService.incr(url);
            }else{
                //超出访问次数
                System.out.println("==============");
                return false;
            }

        }
        return true;
    }
}
